package com.tlx.app.dedao;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tlx.core.util.TConfig;
import com.tlx.core.util.TFileUtils;
import com.tlx.core.util.TSpring;

@Service
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.tlx" })
public class GroupService {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(GroupService.class, args);
        GroupService service = TSpring.getBean(GroupService.class);

        System.setProperty("group.size", "6");

        String dirPath = "D:/0";
        String fileName = "name.json";
        fileName = new File(dirPath, fileName).exists() ? "name" + new SimpleDateFormat("HHmmss").format(new Date()) + ".json" : fileName;

        String json = JSONObject.toJSONString(service.groupAll(dirPath), SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        FileUtils.writeStringToFile(new File(dirPath, fileName), json);
    }

    public Map<String, String> groupAll(String dirPath, String... extArray) {
        Map<String, String> map = new TreeMap<String, String>();
        // 当前目录
        List<String> sonFileList = TFileUtils.getFileListByExt(dirPath, extArray);
        for (String son : sonFileList) {
            String[] gn = splitByNum(son, TConfig.getInt("group.size"));
            String gid = gn[0];
            String gname = gn[1];

            if (StringUtils.isEmpty(gid)) {
                continue;
            }
            if (!map.containsKey(gid)) {
                map.put(gid, gname);
            }
        }

        // 再递归
        List<String> sonDirList = TFileUtils.getDirList(dirPath);
        for (String sonPath : sonDirList) {
            map.putAll(groupAll(sonPath, extArray));
        }

        return map;
    }

    public String[] splitByNum(String name, int size) {
        String[] gn = new String[2];
        name = FilenameUtils.getBaseName(name);
        if (name.length() > size) {
            String gid = name.substring(0, size);
            String gname = name.substring(size);
            gn[0] = gid.trim();
            gn[1] = gname.trim();
        }
        return gn;
    }
}
